import React, { useEffect, useState } from 'react';
import { Card, Form, Input, Button, Table, Tag, Select, Space, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { getOrderList, OrderInfo, OrderListParams } from '../../../services/order';
import './styles.css';
import type { ColumnsType } from 'antd/es/table';

const { Option } = Select;

const OrderList: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<OrderInfo[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 获取订单列表数据
  const fetchOrderList = async (params: OrderListParams = {}) => {
    try {
      setLoading(true);
      const { current = 1, size = 10, ...restParams } = params;
      const response = await getOrderList({
        current,
        size,
        ...restParams,
      });
      setData(response.records);
      setPagination({
        current: response.current,
        pageSize: response.size,
        total: response.total,
      });
    } catch (error) {
      message.error('获取交易列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 首次加载
  useEffect(() => {
    fetchOrderList();
  }, []);

  const columns: ColumnsType<OrderInfo> = [
    {
      title: '基础支撑平台',
      dataIndex: 'platform',
      key: 'platform',
      width: 150,
      render: () => '上海（SH）',

    },
    {
      title: '订单编号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 180,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
      width: 200,
    },
    {
      title: '产品类型',
      dataIndex: 'productType',
      key: 'productType',
      width: 120,
      render: (type: string) => {
        const typeMap: Record<string, string> = {
          DATA_REPORT: '数据报告',
          API: 'API接口',
          MODEL: '模型服务',
        };
        return typeMap[type] || type;
      }
    },
    {
      title: '交易金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (amount: number | undefined) => amount !== undefined ? `¥${amount.toFixed(2)}` : '-',
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: string) => {
        const statusMap = {
          PENDING: { text: '待支付', color: 'warning' },
          PAID: { text: '已支付', color: 'success' },
          CANCELLED: { text: '已取消', color: 'default' },
          REFUNDED: { text: '已退款', color: 'error' },
        };
        const { text, color } = statusMap[status as keyof typeof statusMap] || { text: status, color: 'default' };
        return <Tag color={color}>{text}</Tag>;
      }
    },
    {
      title: '支付状态',
      dataIndex: 'payStatus',
      key: 'payStatus',
      width: 120,
      render: (status: string) => {
        const statusMap = {
          UNPAID: { text: '未支付', color: 'default' },
          PAID: { text: '已支付', color: 'success' },
          PAYMENT_FAILED: { text: '支付失败', color: 'error' },
        };
        const { text, color } = statusMap[status as keyof typeof statusMap] || { text: status, color: 'default' };
        return <Tag color={color}>{text}</Tag>;
      }
    },
    {
      title: '买方',
      dataIndex: 'buyer',
      key: 'buyer',
      width: 150,
    },
    {
      title: '卖方',
      dataIndex: 'seller',
      key: 'seller',
      width: 150,
    },
    {
      title: '支付时间',
      dataIndex: 'payTime',
      key: 'payTime',
      width: 180,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
    }
  ];

  // 处理搜索
  const handleSearch = async (values: any) => {
    try {
      await fetchOrderList({
        ...values,
        current: 1,
        size: pagination.pageSize,
      });
    } catch (error) {
      console.error('搜索失败:', error);
    }
  };

  // 处理重置
  const handleReset = () => {
    form.resetFields();
    fetchOrderList({
      current: 1,
      size: pagination.pageSize,
    });
  };

  // 处理表格变化
  const handleTableChange = (pagination: any, filters: any, sorter: any) => {
    fetchOrderList({
      current: pagination.current,
      size: pagination.pageSize,
      ...form.getFieldsValue(),
      ...filters,
    });
  };

  return (
    <div>
      <Card bordered={false}>
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="orderNo" label="订单编号">
            <Input placeholder="请输入订单编号" allowClear />
          </Form.Item>
          <Form.Item name="productName" label="产品名称">
            <Input placeholder="请输入产品名称" allowClear />
          </Form.Item>
          <Form.Item name="status" label="订单状态">
            <Select placeholder="请选择订单状态" allowClear style={{ width: 200 }}>
              <Option value="PENDING">待支付</Option>
              <Option value="PAID">已支付</Option>
              <Option value="CANCELLED">已取消</Option>
              <Option value="REFUNDED">已退款</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                查询
              </Button>
              <Button onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`
          }}
          onChange={handleTableChange}
        />
      </Card>
    </div>
  );
};

export default OrderList; 